import 'package:flutter/material.dart';

/// 提交回调
typedef ConfirmCallback = bool Function(String newUrl);

/// 备注设置弹窗
class UrlInputDialog extends StatelessWidget {
  final String content;
  final _maxLength = 200;
  final ConfirmCallback confirmCallback;

  final GlobalKey<_NumAndClearTextFieldState> _inputKey = GlobalKey();

  UrlInputDialog(this.content, this.confirmCallback, {Key? key})
      : super(key: key);

  /// 构建标题
  Widget _buildTitle() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: const [
        Padding(
            padding: EdgeInsets.only(left: 25, top: 20, right: 25),
            child: Text(
              "网页地址",
              style: TextStyle(
                  color: Colors.black,
                  fontWeight: FontWeight.bold,
                  fontSize: 18),
            ))
      ],
    );
  }

  /// 构建取消和确认按钮
  Widget _buildActionBtn(context, Function callback) {
    return Wrap(
      children: [
        Padding(
            padding: const EdgeInsets.symmetric(vertical: 20),
            child: Row(
              children: [
                Expanded(
                    child: GestureDetector(
                  onTap: () => Navigator.pop(context),
                  child: const Text(
                    "取消",
                    textAlign: TextAlign.center,
                    style: TextStyle(fontSize: 16, color: Colors.grey),
                  ),
                )),
                Expanded(
                    child: GestureDetector(
                  onTap: () {
                    bool isCanPop = callback();
                    if (isCanPop) {
                      Navigator.pop(context);
                    }
                  },
                  child: const Text(
                    "确定",
                    textAlign: TextAlign.center,
                    style: TextStyle(fontSize: 16, color: Colors.blueAccent),
                  ),
                ))
              ],
            ))
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(16))),
      child: Wrap(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              //标题
              _buildTitle(),
              //输入框
              NumAndClearTextField(
                content,
                _maxLength,
                key: _inputKey,
              ),
              SizedBox.fromSize(size: const Size.fromHeight(12)),
              //取消和确定按钮
              _buildActionBtn(context, () {
                return confirmCallback(
                    _inputKey.currentState!.inputController.text);
              })
            ],
          )
        ],
      ),
    );
  }
}

/// 有文本计数、清除按钮的输入框
class NumAndClearTextField extends StatefulWidget {
  /// 内容
  final String content;

  /// 最大长度
  final int maxLength;

  const NumAndClearTextField(this.content, this.maxLength, {Key? key})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _NumAndClearTextFieldState();
  }
}

class _NumAndClearTextFieldState extends State<NumAndClearTextField> {
  /// 是否有输入内容
  bool _hasInput = false;

  /// 输入框控制器
  var inputController = TextEditingController();

  /// 构建字符长度文字
  Widget _buildTextLength() {
    if (_hasInput) {
      var text = inputController.text.toString();
      var textLength = text.length;
      //计算剩余数量
      var remainingLength = widget.maxLength - textLength;
      return Container(
        padding: const EdgeInsets.only(right: 5),
        child: Text(
          remainingLength.toString(),
          style: const TextStyle(color: Color(0x4d161731), fontSize: 11),
        ),
      );
    }
    return SizedBox.fromSize(size: Size.zero);
  }

  /// 构建清除按钮
  Widget _buildClearBtn() {
    if (_hasInput) {
      return GestureDetector(
        onTap: () {
          // 清除输入
          setState(() {
            inputController.text = "";
            _hasInput = false;
          });
        },
        child: Container(
          height: 17,
          width: 17,
          margin: const EdgeInsets.only(right: 10),
          decoration: BoxDecoration(
              color: Colors.grey, borderRadius: BorderRadius.circular(20)),
          child: const Icon(Icons.clear_sharp, color: Colors.white, size: 13),
        ),
      );
    }
    return SizedBox.fromSize(size: Size.zero);
  }

  @override
  void initState() {
    super.initState();
    // 回显传入的内容
    inputController.text = widget.content;
    // 是否有输出内容
    setState(() {
      _hasInput = inputController.text.isNotEmpty;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
        padding: const EdgeInsets.only(left: 25, top: 12, right: 25),
        child: Container(
          decoration: BoxDecoration(
              color: const Color(0xFFF6F7FC),
              borderRadius: BorderRadius.circular(5)),
          child: Row(
            children: [
              Expanded(
                  child: TextField(
                // 控制器
                controller: inputController,
                // 文本对齐方式
                textAlign: TextAlign.start,
                // 输入类型
                keyboardType: TextInputType.text,
                // 输入框颜色
                // fillColor: Color(0xFFF6F7FC),
                // 自动获取焦点
                autofocus: true,
                // 单行显示
                maxLines: 1,
                // 限制字符长度
                maxLength: widget.maxLength,
                onChanged: (newContent) {
                  setState(() {
                    //widget.content = newContent;
                    if (newContent.isEmpty) {
                      _hasInput = false;
                    } else {
                      _hasInput = true;
                    }
                  });
                },
                // 边框样式
                decoration: const InputDecoration(
                  // 去掉字符数量文字
                  counterText: "",
                  filled: true,
                  fillColor: Colors.transparent,
                  hintText: "请输入地址：",
                  hintStyle: TextStyle(color: Color(0X4D161731), fontSize: 14),
                  // 内容的padding
                  contentPadding: EdgeInsets.all(15),
                  // 获取焦点时的样式
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: Colors.transparent),
                    borderRadius: BorderRadius.zero,
                  ),
                  // 未获得焦点时的样式
                  enabledBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Colors.transparent),
                    borderRadius: BorderRadius.zero,
                  ),
                ),
              )),
              // 剩余字符数量
              _buildTextLength(),
              // 清除按钮
              _buildClearBtn()
            ],
          ),
        ));
  }
}
